<template>
  <!-- 页面-菜单管理 -->
  <div class="innerPageTable-box-OneTwo MenuManage-page innerPageTable-out-flex">
    <!-- 搜索区域 -->
    <SelfAdaption>
      <Form
        :model="searchForm"
        ref="menuSearchForm"
        slot="adaption-bar"
        label-position="top"
        class="ivu-form-no-margin-bottom"
        inline
      >
        <template>
          <!-- <Form-item prop="code" :label="$t('module.serviceManage.enterservicecode')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.code"
              :placeholder="$t('module.serviceManage.servicecode')"
              
              @on-enter="search"
            ></Input>
          </Form-item> -->

          <Form-item prop="name" :label="$t('module.serviceManage.servicename')">
            <Input
              type="text"
              :maxlength="30"
              v-model.trim="searchForm.name"
              :placeholder="$t('module.serviceManage.enterservicename')"
              
              @on-enter="search"
            ></Input>
          </Form-item>

          <!-- 查询\重置按钮 -->
          <Form-item prop="button" class="search-solt-btn">
            <RPButton optType="search" @click="search" />
            <RPButton optType="reset" @click="reset" />
          </Form-item>
        </template>
      </Form>
    </SelfAdaption>
    <InnerPageTable ref="serviceTable" :config="tableConfig">
      <!-- handler bar 查询/重置-->
      <!--
      <div slot="handle-bar">
        <RPButton optType="search" @click="search" />
        <RPButton optType="reset" @click="reset" />
      </div>
      -->
      <!-- table bar 添加-->
      <div slot="table-bar">
        <RPButton optType="create" @click="add" />
        <RPButton optType="delete" @click="deleted" />
      </div>
    </InnerPageTable>
  </div>
</template>
<style lang="less"></style>
<script>
import valueSetAPI from "@/api/valueSetAPI.js";
import menuAPI from "@/api/menuAPI.js";
import { serviceColumns } from "./columns.js";
import ServiceEdit from "./ServiceEdit.vue";
import ServiceConfig from "./ServiceConfig.vue";
import locales from "./locales.js";
import { CoreModuleName } from "@/const.js";
import { getServiceProvider, deleteServiceProvider } from "@/api/serviceMange.js";
import roleApi from "@/api/roleApi.js";


export default {
  name: "service-manage",
  mixins: [locales],
  data() {
    return {
      valueSet: {},
      userInfo: {},
      searchForm: {
        name: "",
      },
    };
  },
  computed: {
    tableConfig() {
      return { loadDataFn: this.queryServiceList, columnsFn: serviceColumns.bind(this), autoFirst: false };
    }
  },
  created: function() {
    this.getValueSet()
    this.init();
  },
  mounted() {},
  methods: {
    getValueSet() {
      let _this = this
      const config = [
        {
          code: "GATEWAY_TYPE",
          attr: "gateway_type",
          targetObj: this.valueSet
        },
        {
          code: "GATEWAY_ROUTE_TYPE",
          attr: "gateway_route_type",
          targetObj: this.valueSet
        },
        {
          code: "GATEWAY_RECEIVE_TYPE",
          attr: "gateway_receive_type",
          targetObj: this.valueSet
        },
        {
          code: "GATEWAY_SEND_TYPE",
          attr: "gateway_send_type",
          targetObj: this.valueSet
        }
      ]
      Promise.all([_this.getValueSetsByConfig(config)]).then(() => {
        this.search()
      })
    },
    getValueSetsByConfig(configs) {
      let asyncArr = [];
      for (let item of configs) {
        asyncArr.push(
          valueSetAPI.getValueSetByCode(item.code).then(data => {
            item.targetObj[item.attr] = data;
          })
        );
      }
      return Promise.all(asyncArr);
    },
    init() {
      let { userInfo } = $store.state[CoreModuleName];
      if (!userInfo) return;
      this.userId = userInfo.id;
      // this.searchForm.tenantCode = userInfo.tenantCode;
    },
    search(page = 1) {
      this.$refs["serviceTable"].load(this.searchForm, page);
    },
    reset() {
      this.$refs["menuSearchForm"].resetFields();
      this.search(1);
    },
    getOperations(menu) {
      let operations = [
          {
            type: "icon",
            icon: "md-create",
            text: this.$t("common.edit"),
            handle: () => {
              this.edit(menu.id, menu);
            }
          },
          {
            type: "icon",
            icon: "ios-settings",
            text: this.$t("module.serviceManage.serviceconfig"),
            handle: () => {
              this.config(menu);
            }
          },
          {
            type: "icon",
            icon: "ios-trash",
            text: this.$t("common.delete"),
            hidden: menu.enabled == 1,
            handle: () => {
              this.deleted(menu);
            }
          }
        ];
      return operations;
    },
    
    edit(id, menu) {
      new this.$pageModal(
        ServiceEdit,
        {
          props: {
            // tenantCode: this.searchForm.tenantCode,
            rowList: menu.id ? menu : {}
          }
        },
        data => {
          data && this.search(this.$refs.serviceTable.param.pageNum);
        }
      );
    },
    add() {
      new this.$pageModal(
        ServiceEdit,
        {
          props: {
            // tenantCode: this.searchForm.tenantCode
          }
        },
        data => {
          data && this.search();
        }
      );
    },
    config() {
      new this.$sidelipPage(ServiceConfig, {
        props: {
          valueSet: this.valueSet,
          tenantCode: this.searchForm.tenantCode
        }
      });
    },
    async deleted(menu) {
      let selectedIds;
      let selectedMenus;
      if (menu && typeof menu.id == "string") {
        selectedIds = [menu.id];
        selectedMenus = [menu];
      } else {
        selectedIds = this.getSelectedIds();
        selectedMenus = this.$refs["serviceTable"].getSelectioned();
        if (selectedIds.length == 0) {
          this.$message.error({
            content: this.$t("module.serviceManage.warning.selectMenu")
          });
          return;
        }
      }
      // 处理删除提示内容
      let deleteTip;
      let deleteTipRole = "";
      for (let item of selectedMenus) {
        await roleApi.getRoleByMenu({ menuIds: [item.id] }).then(res => {
          item.roleByMenu = res.map(i => {
            return i.roleName;
          });
          // 批量删除才需列出各功能组对应的角色
          if (selectedMenus.length > 1 && item.roleByMenu && item.roleByMenu.length) {
            deleteTipRole += "[" + item.menuName + ":" + item.roleByMenu + "]" + "\n";
          }
        });
      }
      // 删除提示：批量删除与单个删除需显示对应删除提示内容格式，否则显示默认提示。
      deleteTip =
        selectedMenus.length > 1 && deleteTipRole
          ? [
              this.$t("module.serviceManage.warning.confirmDelete") + "\n" + this.$t("module.serviceManage.warning.influenceRole") + ":",
              deleteTipRole
            ]
          : selectedMenus.length == 1 && selectedMenus[0].roleByMenu.length != 0
          ? [
              this.$t("module.serviceManage.warning.confirmDelete"),
              this.$t("module.serviceManage.warning.influenceRole") + ":" + selectedMenus[0].roleByMenu
            ]
          : this.$t("module.serviceManage.warning.ensureToDelete");

      // 数组则代表显示严重提示，字符串则为显示普通提示
      if (Array.isArray(deleteTip)) {
        this.$confirm.swarning(deleteTip).then(() => {
          this.deletedAction(selectedIds);
        });
      } else {
        new $confirm(deleteTip, this).then(() => {
          this.deletedAction(selectedIds);
        });
      }
    },
    deletedAction(selectedIds) {
      deleteServiceProvider(selectedIds)
        .then(res => {
          this.$message.success({
            content: this.$t("common.deleteSuccess"),
            duration: 3
          });
          this.search();
        })
        .catch(data => {
          this.$message.error({
            content: data.message,
            duration: 3
          });
        });
    },
    getSelectedIds() {
      let list = this.$refs["serviceTable"].getSelectioned() || [];
      let ids = [];
      for (let u of list) {
        ids.push(u.id);
      }
      return ids;
    },
    getDateString(DateStr) {
      if (DateStr == undefined || DateStr == null || DateStr == "" || DateStr.trim() == "") {
        return "";
      }
      // return DateStr.split(" ")[0];
      let dateList = DateStr.split(" ")[0].split("-");
      let newDateList = [];
      let newItem = "";
      for (let key = 0; key < dateList.length; key++) {
        let newNummber = parseInt(dateList[key]);
        if (newNummber < 10) {
          newNummber = "0" + newNummber;
        }
        newDateList.push(newNummber);
      }
      return newDateList.join("-");
    },
    // 获取菜单列表数据
    queryServiceList({ responseProcess, param }) {
      getServiceProvider(param).then(data => {
        // 状态为有效：禁用复选框，不可删除
        let { records } = data;
        records = this.$root.$options.filters["selection-disabled"](records);
        responseProcess(data);
      });
    }
  }
};
</script>
<style lang="less">
.MenuManage-page {
  .ivu-table {
    .ivu-table-fixed-right {
      .ivu-table-fixed-body {
        .ivu-table-tbody {
          tr {
            .ivu-table-cell {
              width: 109px !important;
            }
          }
        }
      }
    }
  }
}
</style>
